/**
 * 
 */
package com.jysz.certificate.persistence.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.jysz.webcore.ssh.entity.AbstractBaseEntity;

/**
 * 通用dao..
 * 
 * @author <a href="mailto:javaengine@outlook.com">Kaca Rich</a>
 *
 */
@SuppressWarnings("rawtypes")
@Repository
public class CommonDao extends AbstractBaseDao<AbstractBaseEntity, Long> {

	/**
	 * @param classType 实体类型
	 * @param valProperty 实体属性
	 * @param value 属性值
	 * @param entityId 实体ID
	 * @param sqlRestriction 
	 * @return
	 */
	public int findCountByClassType(String classType, String valProperty, Object value, Long entityId, String sqlRestriction) {
		
		Criteria criteria = this.getSession().createCriteria(classType);
		criteria.setProjection(Projections.count(valProperty));
		
		criteria.add(Restrictions.eq(valProperty, value));
		
		if(entityId != null && entityId != 0){
			criteria.add(Restrictions.ne("id", entityId));
		}
		
		if(StringUtils.isNotBlank(sqlRestriction)){
			criteria.add(Restrictions.sqlRestriction(sqlRestriction));
		}
		
		Object obj = criteria.uniqueResult();
		return obj == null ? 0 : Integer.valueOf(obj.toString());
	}

	public List findAll(String classType) {
		Criteria criteria = getSession().createCriteria(classType);
//		for (Criterion c : criterions) {
//			criteria.add(c);
//		}
		return criteria.list();
	}

	public List findAll(String classType, String displayFields, String value, String filterSql) {
		Criteria criteria = getSession().createCriteria(classType);
		
		if(StringUtils.isNotBlank(value)){
			Disjunction disjun = Restrictions.disjunction();
			for(String displayField : displayFields.split(",")){
				disjun.add(Restrictions.like(displayField, value, MatchMode.START));
			}
			criteria.add(disjun);
		}
		
		if(StringUtils.isNotBlank(filterSql)){
			criteria.add(Restrictions.sqlRestriction(filterSql));
		}
		
		return criteria.list();
	}

}
